#
# Bandleader
# Licensed under the GPL
#

import wx
import os
from ChordView import *

class MainWindow(wx.Frame):
    """ The bandleader main window. """

    ID_PLAY = wx.ID_HIGHEST + 1

    def __init__(self, parent, id, title):
        """ Creates the main window. """
        wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(640, 480))

        # Status bar
        self.CreateStatusBar()

        # Control
        self.control = ChordView(self, status_bar=self.GetStatusBar())

        # Menu
        file_menu = wx.Menu()
        file_menu.Append(wx.ID_OPEN, "&Open...", "Opens an existing document")
        file_menu.AppendSeparator()
        file_menu.Append(wx.ID_SAVE, "&Save", "Saves the current document")
        file_menu.Append(wx.ID_SAVEAS, "Save &As...", "Saves the current document under a different name")
        file_menu.AppendSeparator()
        file_menu.Append(wx.ID_EXIT, "E&xit", "Quits the program")

        music_menu = wx.Menu()
        music_menu.Append(MainWindow.ID_PLAY, "&Play", "Plays the current document")

        help_menu = wx.Menu()
        help_menu.Append(wx.ID_ABOUT, "&About Bandleader", "")

        menu_bar = wx.MenuBar()
        menu_bar.Append(file_menu, "&File")
        menu_bar.Append(music_menu, "&Music")
        menu_bar.Append(help_menu, "&Help")
        self.SetMenuBar(menu_bar)

        # Events
        wx.EVT_MENU(self, wx.ID_OPEN, self.on_open)
        wx.EVT_MENU(self, wx.ID_SAVE, self.on_save)
        wx.EVT_MENU(self, wx.ID_SAVEAS, self.on_save_as)
        wx.EVT_MENU(self, wx.ID_EXIT, self.on_exit)

        wx.EVT_MENU(self, MainWindow.ID_PLAY, self.on_play)

        wx.EVT_MENU(self, wx.ID_ABOUT, self.on_about)

        self.Show(True)

    def on_open(self, e):
        """ Opens a file. """
        directory_name = os.getcwd()

        dlg = wx.FileDialog(self, "Choose a file",
                            directory_name, "", "*.*", wx.OPEN)

        if dlg.ShowModal() == wx.ID_OK:
            file_path = dlg.GetPath()
            self.control.open(file_path)

        dlg.Destroy()

    def on_save_as(self, e):
        """ Saves a file under a different name. """
        directory_name = os.getcwd()
        dlg = wx.FileDialog(self, "",
                            directory_name, "", "*.mma", wx.SAVE)

        if dlg.ShowModal() == wx.ID_OK:
            file_path = dlg.GetPath()
            self.control.save_as(file_path)

    def on_save(self, e):
        """ Saves a file. """
        if self.control.is_untitled():
            self.on_save_as(e)
        else:
            self.control.save()

    def on_about(self, e):
        """ Shows an about box. """
        d = wx.MessageDialog(self, "Bandleader v1.0", "About Bandleader", wx.OK)
        d.ShowModal()
        d.Destroy()

    def on_exit(self, e):
        """ Exits the program. """
        self.Close(True)

    def on_play(self, e):
        """ Plays the document. """
        self.control.play()
